package com.sport.facilities.booking.system;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.sport.facilities.booking.db.DatabaseHelper;
import com.sport.facilities.booking.system.httptask.BasicImageTask;
import com.sport.facilities.booking.system.httptask.BasicTask;
import com.sport.facilities.booking.system.httptask.CancelBookingResultTask;
import com.sport.facilities.booking.system.httptask.MakeBookingResultTask;
import com.sport.facilities.booking.system.httptask.OnTaskCompleted;
import com.sport.facilities.booking.system.model.Booking;
import com.sport.facilities.booking.system.model.MakeBookFormModel;
import com.sport.facilities.booking.system.ui.BookingModelListAdaptor;
import com.sport.facilities.booking.system.ui.DialogHelper;
import com.sport.facilities.booking.system.ui.YesAction;

public class MakeBookingListActivity extends Activity implements
		OnItemClickListener {
	private static final String TAG = "MakeBookingListActivity";
	private ListView listView = null;
	private List<Booking> booklist = new ArrayList<Booking>();
	private BookingModelListAdaptor adapter = null;
	private MakeBookFormModel bfm = null;
	private EditText txt_captcha;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.make_booking_list);
		
		txt_captcha = (EditText) findViewById(R.id.text_captcha);
		listView = (ListView) this.findViewById(R.id.makeBookingList);
		Intent i = getIntent();
		try {
			booklist = (List<Booking>) i.getSerializableExtra("bookingList");
			bfm = (MakeBookFormModel) i
					.getSerializableExtra("bookingFormModel");
		} catch (Exception e) {
			DialogHelper.getOkAlertDialog(this, "Error loading data.",
					"Booking list mismatch.").show();
		}

		adapter = new BookingModelListAdaptor(this, booklist);
		listView.setAdapter(adapter);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		listView.setOnItemClickListener(this);
		fnSetFormData(bfm);
	}

	public void setBookingList(List<Booking> booklist) {
		adapter.setBookingList(booklist);
		((BookingModelListAdaptor) adapter).notifyDataSetChanged();
	}

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		adapter.setSelectedPosition(position);
	}

	private void fnSetFormData(MakeBookFormModel bfm) {
		if (bfm != null) {
			TextView usrTextView = (TextView) this.findViewById(R.id.user);
			TextView creditTextView = (TextView) this.findViewById(R.id.credit);
			usrTextView.setText(bfm.getName());
			creditTextView.setText(bfm.getCredit());
		}
	}

	public void submit(View view) {
		

		final MakeBookFormModel bfm = fnGetInputFromView();
		Log.d(TAG, "fnCheckBookPage()" + bfm);
		if (bfm == null) {
			return;
		}
		
		
        Booking bmAddedType = adapter.getSelectedBooking();
        bmAddedType.setBkType("Booking Made");
		final Booking bm = bmAddedType;
		
		
		//if (bm == null) {
		//	DialogHelper.getOkAlertDialog(this, "No Record selected.",
		//			"Please select a record.").show();
		//	return;
		//}
		
		/*
		if (txt_captcha.toString().matches("")	|| txt_captcha.getText().toString().length() <= 3) {
			DialogHelper.getOkAlertDialog(this, "Please fill in the data.",
					"Please fill in the captcha value.").show();
			//return;
		}
		*/


		
		fnGetCaptchaFromView();
		final MakeBookFormModel bfms = this.bfm;
		final MakeBookingListActivity mbla = this;
		OnTaskCompleted action = new OnTaskCompleted() {
			public void onTaskCompleted(Object result) {
				YesAction yesAction = new YesAction() {
					public void fnDoYesAction() {
						mbla.finish();

						//Context ctx = getBaseContext();
						//Intent intent = new Intent(ctx,
						//		FacebookActivity.class);		
						

					}
				};
				
				DialogHelper.getOkAlertDialog(mbla, "Booking Success!", "",yesAction)
						.show();
				//txt_captcha.setText("");
				
				//fnaddactivitytodb(bm);
				fngofacebook(bm);
				fnAddAlarm(bm);
				
			}

			public void onTaskFailed(String errMessage) {
				fnLoadBookingCaptcha();
				DialogHelper.getOkAlertDialog(mbla, "Error In Booking",
						errMessage).show();

				txt_captcha.setText(""); //remove the old captcha when error 
			}
		};
		final MakeBookingResultTask bmrt = new MakeBookingResultTask(mbla,
				action);

		YesAction yesAction = new YesAction() {
			public void fnDoYesAction() {
				bmrt.fnMakeBooking(bm, bfms);
			}
		};

		String message = "Date:      " + bm.getDate() + "\n" + "Time:     "
				+ bm.getTime() + "\n" + "Centre:   " + bm.getCentre() + "\n"
				+ "Activity: " + bm.getActivity() + "\n" + "Price: "
				+ bm.getPrice() + "\n";
		DialogHelper.getYesNoDialog(mbla,
				"Are you sure you want to book this?", message, yesAction).show();
	}
	
	private void fnLoadBookingCaptcha() {
		final MakeBookingListActivity mbActivity = this;
		OnTaskCompleted completeAction = new OnTaskCompleted() {
			public void onTaskCompleted(Object s) {
				ImageView iv = (ImageView) findViewById(R.id.captcha);
				iv.setImageBitmap((Bitmap) s);
			}

			public void onTaskFailed(String errMessage) {
				Log.e(TAG, errMessage);
				DialogHelper.getOkAlertDialog(mbActivity,
						"Error In Loading Captcha", errMessage).show();
			}
		};
		BasicImageTask bit = new BasicImageTask(this, completeAction);
		bit.execute(BasicTask.PATH_BOOK_IMG);
	}
	
	private void fnGetCaptchaFromView() {
		EditText txt_captcha = (EditText) findViewById(R.id.text_captcha);
		bfm.setKaptchaValue(txt_captcha.getText().toString());
	}

	public void back(View view) {
		finish();
	}
	
	@Override
	public void onResume() {
		super.onResume();
		fnLoadBookingCaptcha();
	}
	
	

	private MakeBookFormModel fnGetInputFromView() {
		if (this.bfm == null) {
			return null;
		}

        Booking bmAddedType = adapter.getSelectedBooking();
        //bmAddedType.setBkType("Booking Made");
		//final Booking bm = bmAddedType;
		
		
		if (bmAddedType == null) {
			DialogHelper.getOkAlertDialog(this, "No Record selected.",
					"Please select a record.").show();
			return null;
		}

		if (txt_captcha.getText().toString().equalsIgnoreCase("")
				|| txt_captcha.getText().length() <= 3) {
			DialogHelper.getOkAlertDialog(this, "Please fill in the data.",
					"Please fill in the captcha value.").show();
			return null;
		}


		return bfm;
	}

	
	
	public void fnaddactivitytodb(Booking bkdetail){

		DatabaseHelper db = new DatabaseHelper(this);

		/**
		 * CRUD Operations
		 * */
		// Inserting activity
		Log.d("Insert: ", "Inserting ..");
		db.addActivity(new Booking(bkdetail.getActivity(),bkdetail.getBkType(), bkdetail.getCentre(),
				bkdetail.getCourt(), bkdetail.getDate(), bkdetail.getTime(), bkdetail.getalarmId()));
	}
	
	public void fngofacebook(final Booking bkdetail){
		
		YesAction yesAction = new YesAction() {
			public void fnDoYesAction() {

				Context ctx = getBaseContext();
				Intent i = new Intent(ctx, FacebookActivity.class);

				i.putExtra("bookObj", bkdetail);
				startActivity(i);

				//Context ctx = getBaseContext();
				//Intent intent7 = new Intent(ctx,
				//		FacebookActivity.class);

				//intent7.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				//ctx.startActivity(intent7);
			}
		};
		
		// alert box share box
		DialogHelper
				.getYesNoDialog(
						this,
						"Share Booking",
						"Share this action on FACEBOOK?",
						yesAction)
				.show();
		
	}
	
	
	

	public void fnAddAlarm(Booking bkdetail){
		
		//Log.d("Alarm Service", "asfasdfasdf");
		//seting tmp bkdetail data
		//Booking bkdetail = new Booking();
		//bkdetail.setActivity("Table tennis");
		//bkdetail.setBkType("Booking Made");
		//bkdetail.setCentre("SHAWSPORTS");
		//bkdetail.setCourt("TT1");
		//bkdetail.setDate("01-Mar-2013");
		//bkdetail.setTime("01:08-09:29");
		
		int randomNumber = (int) (new Date().getTime());				
		
		String splitdate[] = bkdetail.getDate().split("-"); 
		
		
		Date date = null;
		try {
			date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(splitdate[1]);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    Calendar cals = Calendar.getInstance();
	    cals.setTime(date);
	    int month = cals.get(Calendar.MONTH);
		
		
		Calendar cal = Calendar.getInstance(); // for using this you need to
												// import java.util.Calendar;

		// add minutes to the calendar object
		cal.set(Calendar.MONTH, month); //0=Jan 1=Feb 2=Mar etc.....
		cal.set(Calendar.YEAR, Integer.parseInt(splitdate[2]));
		cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(splitdate[0]));
		cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(bkdetail.getTime().substring(0, 2)));
		cal.set(Calendar.MINUTE, Integer.parseInt(bkdetail.getTime().substring(3, 5)));
		cal.add(Calendar.MINUTE, -30);

		int alarmservice_Id = randomNumber;
		
		Log.d("Setting Alarm Service",  "Alarm ID: "+ alarmservice_Id + "---------" + Integer.parseInt(splitdate[0]) + "-" + month + "-" + Integer.parseInt(splitdate[2]) + " Time:" + Integer.parseInt(bkdetail.getTime().substring(0, 2)) + ":" + Integer.parseInt(bkdetail.getTime().substring(3, 5)));
		//cal.add(Calendar.SECOND, 5);     

		Intent alarmintent = new Intent(getApplicationContext(),
				AlarmReceiver.class);
		alarmintent.putExtra("title", "Polyu Sport Facilities Booking System");
		alarmintent.putExtra("note", bkdetail.getActivity() + " Notification");

		
		PendingIntent sender = PendingIntent.getBroadcast(
				getApplicationContext(), alarmservice_Id, alarmintent,
				PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

		
		//PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), (int) alarm_id, alarmintent, PendingIntent.FLAG_CANCEL_CURRENT);
		
		AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
		
		
		DatabaseHelper db = new DatabaseHelper(this);

		/**
		 * CRUD Operations
		 * */
		// Inserting activity 
		Log.d("Insert: ", "Inserting ..");
		db.addActivity(new Booking(bkdetail.getActivity(),bkdetail.getBkType(), bkdetail.getCentre(),
				bkdetail.getCourt(), bkdetail.getDate(), bkdetail.getTime(), alarmservice_Id));
	}
	
	
	
	
	
	
}
